package com.jvtd.eyl.ui.main.home.read.video;

import android.content.Context;
import android.content.res.Configuration;
import android.databinding.DataBindingUtil;
import android.net.Proxy;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ext.rtmp.RtmpDataSourceFactory;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource;
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.jvtd.eventBus.EventCenter;
import com.jvtd.eyl.R;
import com.jvtd.eyl.base.BaseMvpFragment;
import com.jvtd.eyl.bean.binding.BookBean;
import com.jvtd.eyl.databinding.FragmentVideoBinding;
import com.jvtd.eyl.ui.main.home.read.ReadMvpView;
import com.jvtd.eyl.ui.main.home.read.ReadPresenter;
import com.jvtd.eyl.utils.videoplayer.CustomSource;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.cache.CacheFactory;
import com.shuyu.gsyvideoplayer.cache.ProxyCacheManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager;
import com.shuyu.gsyvideoplayer.player.PlayerFactory;
import com.shuyu.gsyvideoplayer.player.SystemPlayerManager;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import tv.danmaku.ijk.media.exo2.Exo2PlayerManager;
import tv.danmaku.ijk.media.exo2.ExoMediaSourceInterceptListener;
import tv.danmaku.ijk.media.exo2.ExoPlayerCacheManager;
import tv.danmaku.ijk.media.exo2.ExoSourceManager;

/**
 * 视频预览
 * 作者:chenlei
 * 时间:2018/11/15 9:49 AM
 */
public class VideoFragment extends BaseMvpFragment implements ReadMvpView{
    @Inject
    ReadPresenter<ReadMvpView> mPresenter;
    private FragmentVideoBinding mBinding;
    private OrientationUtils orientationUtils;

    private boolean isPlay;
    private boolean isPause;

    private static final String SELECT_KEY = "SELECT_KEY";
    public static final int TYPE_RTMP = 4;
    private BookBean mBookBean;

    public static VideoFragment newInstance(BookBean bookBean) {
        Bundle args = new Bundle();
        args.putParcelable(SELECT_KEY,bookBean);
        VideoFragment fragment = new VideoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void onDestroyView() {
        mPresenter.onDetach();
        if (isPlay && mBinding.detailPlayer != null)
            getCurPlay().release();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
        super.onDestroyView();
    }

    @Override
    protected View getLayout(LayoutInflater inflater, @Nullable ViewGroup container) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_video, container, false);
        return mBinding.getRoot();
    }

    @Override
    protected void initViewAndData() {
        mPresenter.onAttach(this);
        if (getArguments() != null) {
            mBookBean = getArguments().getParcelable(SELECT_KEY);
        }
        if (mBookBean == null)
        {
            showMessage(R.string.error_message);
            return;
        }

        resolveNormalVideoUI();

        //设置旋转
        orientationUtils = new OrientationUtils(getActivity(), mBinding.detailPlayer);
        orientationUtils.setEnable(false);

        PlayerFactory.setPlayManager(Exo2PlayerManager.class);
        ExoSourceManager.setExoMediaSourceInterceptListener((dataSource, preview, cacheEnable, isLooping, cacheDir) -> {
            Uri contentUri = Uri.parse(dataSource);
            int contentType = Util.inferContentType(dataSource);
            switch (contentType) {
                case C.TYPE_SS:
                    return new SsMediaSource.Factory(
                            new DefaultSsChunkSource.Factory(CustomSource.getDataSourceFactory(getContext(), preview)),
                            new DefaultDataSourceFactory(getContext(), null,
                                    CustomSource.getHttpDataSourceFactory(getContext(), preview))).createMediaSource(contentUri);
                case C.TYPE_DASH:
                    return new DashMediaSource.Factory(new DefaultDashChunkSource.Factory(CustomSource.getDataSourceFactory(getContext(), preview)),
                            new DefaultDataSourceFactory(getContext(), null,
                                    CustomSource.getHttpDataSourceFactory(getContext(), preview))).createMediaSource(contentUri);
                case C.TYPE_HLS:
                    return new HlsMediaSource.Factory(CustomSource.getDataSourceFactory(getContext(), preview)).createMediaSource(contentUri);
                case TYPE_RTMP:
                    RtmpDataSourceFactory rtmpDataSourceFactory = new RtmpDataSourceFactory(null);
                    return new ExtractorMediaSource.Factory(rtmpDataSourceFactory)
                            .setExtractorsFactory(new DefaultExtractorsFactory())
                            .createMediaSource(contentUri);
                case C.TYPE_OTHER:
                default:
                    return new ExtractorMediaSource.Factory(CustomSource.getDataSourceFactory(getContext(), preview))
                            .setExtractorsFactory(new DefaultExtractorsFactory())
                            .createMediaSource(contentUri);
            }
        });
//        CacheFactory.setCacheManager(ExoPlayerCacheManager.class);
        GSYVideoOptionBuilder gsyVideoOption = new GSYVideoOptionBuilder();
        gsyVideoOption.setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setAutoFullWithSize(true)
                .setShowFullAnimation(false)
                .setNeedLockFull(false)
                .setUrl(mBookBean.getUrl())
                .setCacheWithPlay(false)
                .setVideoTitle(mBookBean.getName())
                .setVideoAllCallBack(new GSYSampleCallBack() {
                    @Override
                    public void onPrepared(String url, Object... objects) {
                        super.onPrepared(url, objects);
                        //开始播放了才能旋转和全屏
                        orientationUtils.setEnable(true);
                        isPlay = true;
                    }

                    @Override
                    public void onEnterFullscreen(String url, Object... objects) {
                        super.onEnterFullscreen(url, objects);
                    }

                    @Override
                    public void onAutoComplete(String url, Object... objects) {
                        super.onAutoComplete(url, objects);
                    }

                    @Override
                    public void onClickStartError(String url, Object... objects) {
                        super.onClickStartError(url, objects);
                    }

                    @Override
                    public void onQuitFullscreen(String url, Object... objects) {
                        super.onQuitFullscreen(url, objects);
                        if (orientationUtils != null) {
                            orientationUtils.backToProtVideo();
                        }
                    }
                })
                .setLockClickListener((view, lock) -> {
                    if (orientationUtils != null) {
                        //配合下方的onConfigurationChanged
                        orientationUtils.setEnable(!lock);
                    }
                })
                .setGSYVideoProgressListener((progress, secProgress, currentPosition, duration) -> {
                })
                .build(mBinding.detailPlayer);

        mBinding.detailPlayer.getFullscreenButton().setOnClickListener(v -> {
            //直接横屏
            orientationUtils.resolveByClick();

            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
            mBinding.detailPlayer.startWindowFullscreen(mContext, true, true);
        });

//        mPresenter.addBook(Collections.singletonList(mBookBean));
        addBookSuccess(Collections.singletonList(mBookBean));
    }

    /**
     * 恢复
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    @Override
    public void onResume() {
        super.onResume();
        if (mBinding.detailPlayer != null) {
            getCurPlay().onVideoResume();
            isPause = false;
        }
    }

    /**
     * 暂停
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    @Override
    public void onPause() {
        super.onPause();
        if (mBinding.detailPlayer != null) {
            getCurPlay().onVideoPause();
            isPause = true;
        }
    }

    /**
     * 界面显示方法
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (mBinding.detailPlayer != null && isPause) {
            getCurPlay().onVideoResume();
            isPause = false;
        }
    }

    /**
     * 界面隐藏方法
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (mBinding.detailPlayer != null && !isPause) {
            getCurPlay().onVideoPause();
            isPause = true;
        }
    }

    @Override
    public void addBookSuccess(List<BookBean> bookBeans) {
        super.addBookSuccess(bookBeans);
        mPresenter.addBrowse(mBookBean);
    }

    /**
     * 返回键方法
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    public boolean onKeyDownBack(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (orientationUtils != null) {
                orientationUtils.backToProtVideo();
            }
        }
        return !GSYVideoManager.backFromWindowFull(getActivity());
    }

    /**
     * 旋转监听
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            mBinding.detailPlayer.onConfigurationChanged(getActivity(), newConfig, orientationUtils, true, true);
        }
    }

    /**
     * 隐藏返回键标题
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    private void resolveNormalVideoUI() {
        //增加title
        mBinding.detailPlayer.getTitleTextView().setVisibility(View.GONE);
        mBinding.detailPlayer.getBackButton().setVisibility(View.GONE);
    }

    /**
     * 获得当前播放器
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    private GSYVideoPlayer getCurPlay() {
        if (mBinding.detailPlayer != null && mBinding.detailPlayer.getFullWindowPlayer() != null) {
            return  mBinding.detailPlayer.getFullWindowPlayer();
        }
        return mBinding.detailPlayer;
    }
}
